package com.xbongbong.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.parent.abstracts.AbstractBusinessLinkProductService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.util.SaasLinkProductUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 吴峰
 * @date 2022/06/13 15:37
 */
@Service("refundLinkProductService")
public class RefundLinkProductServiceImpl extends AbstractBusinessLinkProductService {

    @Resource
    private ContractModel contractModel;
    @Resource
    private ContractProductModel contractProductModel;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.REFUND.getCode());
    }

    @Override
    public void analysisListProductData(FormDataListDTO formDataListDTO, List<PaasFormDataEntityExt> paasFormDataESList, List<FieldAttrEntity> explainList, Integer page, Integer pageSize) throws XbbException {
        if (CollectionUtils.isEmpty(paasFormDataESList)) {
            return;
        }
        String corpid = formDataListDTO.getCorpid();
        boolean productNameNeedHide = getProductNameVisible(formDataListDTO.getLoginUser(), corpid);

        Map<String, FieldAttrEntity> explainMap = explainList.stream().collect(Collectors.toMap(FieldAttrEntity:: getAttr, attr-> attr));
        if (!explainMap.containsKey(RefundEnum.PRODUCTS.getAttr())){
            return ;
        }
        FieldAttrEntity fieldAttrEntity = explainMap.get(RefundEnum.PRODUCTS.getAttr());
        List<FieldAttrEntity> linkProductList = SaasLinkProductUtil.listProductLinkKeyField(fieldAttrEntity);


        explainMap.put(RefundEnum.PRODUCTS.getAttr(), fieldAttrEntity);
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("pageNumGroup",pageSize);
        map.put("startGroup",page);
        if (Objects.isNull(pageSize)){
            map.put("orderByStrGroup", BasicConstant.SORT);
        } else {
            map.put("orderByStr", BasicConstant.SORT);
        }
        Map<Long, Long> refundAndContract = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> refundContractIdList = new ArrayList<>();
        refundContractIdList.add(-1L);
        Map<Long,Long> refundProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt entity : paasFormDataESList) {
            JSONObject refundObject = entity.getData();
            if (refundObject == null) {
                break;
            }
            Long refConId = refundObject.getLong(RefundEnum.RED_CONTRACT_ID.getAttr());
            refundContractIdList.add(refConId);
            refundAndContract.put(refConId,entity.getId());
            refundProductMap.put(refConId,entity.getDataId());
        }
        map.put("contractIdIn", refundContractIdList);
        map.put("type",XbbRefTypeEnum.REFUND.getCode());
        if (Objects.isNull(pageSize)) {
            map.put("groupByStr", "contract_id");
            map.put(ParameterConstant.ORDER_BY_STR_GROUP, BasicConstant.SORT);
        }else {
            map.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        }
        List<ContractProductEntity> list = contractProductModel.findEntitys(map);
        Map<Long, List<JSONObject>> productDataMap = new HashMap<>(paasFormDataESList.size());
        Set<Long> productIdSet = new HashSet<>();
        for (ContractProductEntity item : list) {
            Long contractId = item.getContractId();
            if (refundProductMap.containsKey(contractId)) {
                JSONObject productData = contractModel.formatSingleRefundProduct(item);
                if (Objects.isNull(productData.get(ProductEnum.PRICE.getAttr()))) {
                    productData.put(ProductEnum.PRICE.getAttr(),item.getPrice());
                }
                productData.put(StringConstant.DATA_ID,productData.getLong(SelectProductEnum.PRODUCT.getAttr()));
                productData.put(SelectProductEnum.PRODUCT.getAttr(),productNameNeedHide ? null : item.getProductName());
                List<JSONObject> productDataList = productDataMap.getOrDefault(refundProductMap.get(contractId), new ArrayList<>());
                productDataList.add(productData);
                productDataMap.put(refundProductMap.get(contractId),productDataList);
                productIdSet.add(item.getProductId());
            }
        }
        // 将数据放到关联产品中
        setLinkProduct(corpid, paasFormDataESList, linkProductList, productIdSet, productDataMap, RefundEnum.PRODUCTS.getAttr());
    }
}
